package top.forgirl.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import top.forgirl.domain.Login;
import top.forgirl.domain.dto.LoginDo;
import top.forgirl.mapper.LoginMapper;
import top.forgirl.util.JwtUtil;

@Service
public class LoginService {

    @Autowired
    private LoginMapper loginMapper;

    public LoginDo login(Login login) {
        Login loginMsg = loginMapper.selectOne(login);

        if (ObjectUtils.isEmpty(loginMsg)) {
            return null;
        }

        return new LoginDo(JwtUtil.generateJwt(loginMsg.getPrincipal()), loginMsg.getLimit(), login.getPrincipal());

    }

    public boolean checkUniquePrincipal(String principal) {
        Login login = loginMapper.checkUniquePrincipal(principal);
        if (login != null) {
            return false;
        }
        return true;
    }

    public boolean updateLogin(Login login) {
        int result = loginMapper.update(login);
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }

    public Login register(String principal, String credential) {
        Login login = new Login();
        login.setPrincipal(principal);
        login.setCredential(credential);

        int insert = loginMapper.insert(login);
        if (insert > 0) {
            return login;
        }
        return null;
    }
}
